<template>
     <van-popup v-model="show" round position="bottom">
        <van-datetime-picker
            v-if="type!='year'"
            ref="date"
            v-model="datetime"
            :min-date="minDate"
          :max-date="maxDate"
          :type="type"
          @confirm="confirmDate"
          @cancel="cancelDate"
        />
        <van-picker
            v-else
            ref="year"
            :columns="yearColumns"
            show-toolbar
            @cancel="cancelDate"
            @confirm="confirmDate"
        />
      </van-popup>
</template>

<script>
import { parseTime } from '@/utils'
export default {
  name: 'xyzFieldDatePopup',
  model: {
    prop: 'show'
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    minDate: {
      type: Date,
      default: () => {
        return new Date(2000, 0, 1)
      }
    },
    maxDate: {
      type: Date,
      default: () => {
        return new Date(2035, 12, 30)
      }
    },
    type: {
      type: String,
      default: 'date'
    },
    formatter: {
      type: String,
      default: '{y}/{m}/{d}'
    }
  },
  data () {
    return {
      yearColumns: [],
      currentDate: '',
      datetime: new Date(),
      showDate: false
    }
  },
  created () {
    this.type == 'year' && this.getYear()
  },
  computed: {

  },
  methods: {
    getYear () { // 设置只选年份时候的数据
      const maxY = Number.parseInt(parseTime(this.maxDate, '{y}'))
      const minY = Number.parseInt(parseTime(this.minDate, '{y}'))
      for (let i = maxY; i >= minY; i--) {
        this.yearColumns.push(i)
      }
    },
    confirmDate (val) { // 确定
      this.showDate = false
      this.currentDate = this.type == 'year' ? val : parseTime(val, this.formatter)
      this.$emit('confirm', this.currentDate)
    },
    cancelDate () {
      this.showDate = false
      this.$emit('cancel')
    }
  },
  watch: {
    showDate (val) {
      this.$emit('input', val)
    },
    show (val) {
      this.showDate = val
    }
  }
}
</script>
